package com.tgy.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 文件上传下载工具类
 */
@Component
public class AppFileUtils {

    private final static String DEFAULT_IMAGE_PATH = "default/moren.png";    //默认图片路径
    private static String UPLOAD_PATH;      //默认值,存储文件（图片）的地址
    private final static String TEMP;

    //静态模块用于从配置文件种获取到设置的存储位置。方便于以后项目迁移时好做更改
    static {
        InputStream stream = AppFileUtils.class.getClassLoader().getResourceAsStream("file.properties");
        Properties properties = new Properties();
        try {
            properties.load(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        UPLOAD_PATH = properties.getProperty("fileUploadPath");
        TEMP = properties.getProperty("temp");
    }

    /**
     * 根据旧名字得到新名字
     *
     * @param oldFileName   就名字
     */
    private static String createNewFileName(String oldFileName) {
        String stuff = oldFileName.substring(oldFileName.lastIndexOf("."));
        return IdUtil.simpleUUID().toUpperCase() + stuff;
    }

    /**
     * 文件下载(下载总出问题，显示图片没问题)
     *
     * @param path      路劲
     */
    public static ResponseEntity<Object> createResponseEntity(String path) {
        //1.构造文件对象
        File file = new File(UPLOAD_PATH, path);
        if (file.exists()) {
            //将下载的文件封装成byte[]
            byte[] bytes = null;
            bytes = FileUtil.readBytes(file);

            String fileName = IdUtil.randomUUID() + path.substring(path.lastIndexOf("."));

            //创建封装响应头信息的对象
            HttpHeaders headers = new HttpHeaders();

            //封装响应内容类型(APPLICATION_OCTET_STREAM响应的内容不限)
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            //设置下载文件的名称
            headers.setContentDispositionFormData("attachment", fileName);
            //创建ResponseEntity对象
//            ResponseEntity entity=new ResponseEntity(bytes,headers, HttpStatus.CREATED);
            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
        }
        return null;
    }

    /**
     * 文件下载
     *
     * @param path  路劲
     */
    public static File createResponseEntity2(String path, HttpServletResponse response, String name) throws IOException {
        //设置默认的下载文件名
        //避免文件名中文乱码，将UTF8打散重组成ISO-8859-1编码方式
        name = new String(name.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        //设置响应流中文件进行下载,响应头的属性默认是inline 表示能显示就显示,不能显示就下载
        //需要将Content-Disposition的属性值修改为attachment（下载）。filename后面跟的就是下载时显示的名称
        response.setHeader("Content-Disposition", "attachment;filename=" + name);
        //把二进制流放入到响应体中.
        ServletOutputStream os = response.getOutputStream();
        File file = new File(UPLOAD_PATH,path);
        //读取文件为二进制流
        byte[] bytes = FileUtil.readBytes(file);
        os.write(bytes);
        os.flush();
        os.close();
        return file;
    }


    /**
     * 在添加和修改时去掉图片名字后缀的'_temp'
     */
    public static String renameFile(String goodsimg) {
        File file = new File(UPLOAD_PATH, goodsimg);
        String replace = goodsimg.replace(TEMP, "");
        if (file.exists()) {
            file.renameTo(new File(UPLOAD_PATH, replace));
        }
        return replace;
    }

    /**
     * 修改图片后，根据老路径删除以前图片
     *
     * @param oldPath   旧路劲
     */
    public static void removeFileByPath(String oldPath) {
        File file = new File(UPLOAD_PATH, oldPath);
        if (file.exists()) {
            file.delete();
        }
    }

    /**
     * 判断是不是最新图片
     */
    public static Boolean determineOldPicture(String newPath){
        if (!(null != newPath && newPath.equals(DEFAULT_IMAGE_PATH))) {
            //不是默认图片且以"_temp"结尾，说明是新图片
            return newPath.endsWith(TEMP);
        }
        return false;
    }


    /**
     * 文件上传
     */
    public static Map<String,String> uploadFile(MultipartFile mf) {

        Map<String,String> map = new HashMap<>();

        //1.得到文件名
        String oldFileName = mf.getOriginalFilename();
        //2.根据旧名字得到新的名字
        String newFileName = AppFileUtils.createNewFileName(oldFileName);
        //3.得到当前日期的字符串
        String dirName = DateUtil.format(new Date(), "yyyy-MM-dd");
        //4.构造文件夹
        File dirFile = new File(AppFileUtils.UPLOAD_PATH + dirName);
        //5.判断是否存在
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        //6.构造文件对象
        File file = new File(dirFile, newFileName + TEMP);
        //7.把mf里面的图片信息写入file
        try {
            mf.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        map.put("oldFileName",oldFileName);
        map.put("newFileName",newFileName);
        map.put("path",dirName + "/" + newFileName + TEMP);
        map.put("stuff",oldFileName.substring(oldFileName.lastIndexOf(".")));

        return map;
    }
}
